package com.mlnx.netty.app.ecg.handler;


import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.mptp.mptp.body.Body;
import com.mlnx.mptp.mptp.head.QoS;
import com.mlnx.netty.app.ecg.message.EcgMessage;
import com.mlnx.netty.app.ecg.message.PublishMessage;
import com.mlnx.netty.app.ecg.session.core.DeviceSession;
import com.mlnx.tp.base.model.DeviceType;

import java.util.Date;

import io.netty.channel.ChannelHandlerContext;

public class PushHandle extends BaseSimpleChannelInboundHandler<PublishMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PublishMessage msg)
            throws Exception {

        String deviceId = msg.getBody().getDeviceId();
        final Body body = msg.getBody();

        if (body.getDeviceState() != null) {
            log.info("收到设备状态：" + body.getDeviceState() + "  时间：" + new Date(body.getPacketTime()));
        }

        DeviceSession session = (DeviceSession) sessionManager.getSession(ctx.channel());

        switch (msg.getDeviceType()) {
            // 心电设备发送给用户的主题
            case ECG_DEVICE:

                EcgMessage ecgMessage = new EcgMessage();
                ecgMessage.setDeviceType(DeviceType.ECG_DEVICE);
                ecgMessage.setDeviceId(deviceId);
                ecgMessage.setEcgData(body.getEcgBody().getEcgData());
                ecgMessage.setEcgDeviceInfo(body.getEcgBody().getEcgDeviceInfo());
                ecgMessage.setDeviceInfoUpdate(body.getEcgBody().isDeviceInfoUpdate());
                ecgMessage.setPacketTime(body.getPacketTime());

                ctx.fireChannelRead(ecgMessage);
                break;
            default:
                break;
        }

        if (QoS.LEAST_ONE.equals(msg.getQoS())) {
            MpPacket packet = null;
            if (body.getMessageId() == null) {
                packet = new MpPacket().pushAck(DeviceType.SERVER, null,
                        ResponseCode.LOST_MESSAGE_ID);
            } else {
                packet = new MpPacket().pushAck(DeviceType.SERVER,
                        body.getMessageId(), ResponseCode.SUCESS);
            }
            ctx.channel().writeAndFlush(packet);
        }
    }
}
